package com.spring.tools;

import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import com.spera.shopoa.util.ShopOaSessionUtil;
import com.spera.shopoa.util.ShopOaSessionUtil.OaUser;
import com.spring.common.web.model.TracelogboWithBLOBs;
import com.spring.security.core.util.ApplicationUtils;
import com.spring.security.web.dao.JedisCache;
import com.spring.security.web.model.BaseResult;


public class MyTools {
	/**
	 * page_index转换rows
	 * @param page_size
	 * @param page_index
	 * @param skip
	 * @param rows
	 * @return
	 */
	public static HashMap pageIndexToSkip(String page_size,String page_index,String skip,String rows){
		
		int pagesize=20;
		int pageindex=1;
		int skipint=0;
		int rowsint=20;
		
		if(page_size!=null&&page_index!=null){
			
			 pagesize=Integer.parseInt(page_size);
			 pageindex=Integer.parseInt(page_index);
			
			skipint=pagesize*(pageindex-1);
			rowsint=pagesize;
			
		}else if(skip!=null&&rows!=null){
			
			 skipint=Integer.parseInt(skip);
			 rowsint=Integer.parseInt(rows);
			
		}
		
		
		HashMap hm=new HashMap();
		hm.put("skip", skipint);
		hm.put("rows", rowsint);
		
		return hm;
	}
	
	
	
	public static HashMap checkIsNotNull(String... parameter){
		HashMap hm = null;
		for(int i=0;i<parameter.length;i++){
			if(parameter[i]==null||parameter[i].equals("")){

				hm=new HashMap();
				hm.put(ApplicationUtils.STATUS, "0");
				hm.put(ApplicationUtils.MSG, "请输入必要的参数");
				return hm;
			}
			
			
		}
			return hm;
	
	}

	public static String timestampToString(String timestamp) throws Exception {
		
		Timestamp ts = new Timestamp(Integer.parseInt(timestamp)*1000);
		
		DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time = null;

		time = sdf.format(ts);

		return time;
	}
	
	public static String getOrderNumber(){
	Date d=new Date();
	SimpleDateFormat sFormat = new SimpleDateFormat("yyyyMMddHHmmss");
	String date=sFormat.format(d);
	String timestamp=String.valueOf(System.currentTimeMillis());
	String minitime=timestamp.substring(timestamp.length()-3, timestamp.length());
	
	
	int[] r=ApplicationUtils.randomArray(100000 , 999999, 1);
	
	String orderNumber=date+minitime+r[0];

	return orderNumber;
	}
	
	public static String ObjectToString(Object o){
		String r=String.valueOf(o);
		if(r.equals("")||r.equals("null")){
			r=null;
		}
		return r;
	}	
	
	public static BaseResult MapToBaseResult(Map<String,Object> map){
		String status=ObjectToString(map.get("status"));
		String msg=ObjectToString(map.get("msg"));
		Object dataset=map.get("dataset");
		
		BaseResult baseResult=new BaseResult(status,msg,dataset);
		return baseResult;
	}	
	public static TracelogboWithBLOBs getLog(JedisCache jedisCache,String token,HttpServletRequest request){
		TracelogboWithBLOBs tl = getLogByRequest(request);
		
		Map<String, String> user=jedisCache.hgetAll(token);
		String userID=user.get("user_id");
		String userName=user.get("user_name");
		String deviceCategory=user.get("deviceCategory");
		if(deviceCategory!=null){
			tl.setDevicecategory(Integer.parseInt(deviceCategory));
		}
		tl.setInitialoperatorid(userID);
		tl.setInitialoperatorname(userName);
		return tl;
	}

	public static TracelogboWithBLOBs getOaLogByRequest(HttpServletRequest request){	
		TracelogboWithBLOBs tl=getLogByRequest(request);
		
		OaUser oaUser = ShopOaSessionUtil.getOaUser(request);
		String workID=oaUser.getOa_user_id();
		String workName=oaUser.getOa_user_name();
		
		tl.setDevicecategory(0);
		
		tl.setInitialoperatorid(workID);
		tl.setInitialoperatorname(workName);
		return tl;
	}

	public static TracelogboWithBLOBs getLogByRequest(HttpServletRequest request){
		
		String url = request.getRequestURL()+"";	
		String ipaddress = getIpAddr(request);
		
		TracelogboWithBLOBs tl=new TracelogboWithBLOBs();
		tl.setIpaddress(ipaddress);
		tl.setUrl(url);
		return tl;
	}



	public static String getIpAddr(HttpServletRequest request) {
		 String ip = request.getHeader("x-forwarded-for");
		 System.out.println(ip+"ip");
		 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		  ip = request.getHeader("Proxy-Client-IP");
		 }
		 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		  ip = request.getHeader("WL-Proxy-Client-IP");
		 }
		 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		  ip = request.getRemoteAddr();
		 }
		 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		  ip = request.getHeader("http_client_ip");
		 }
		 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		  ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		 }
		 // 如果是多级代理，那么取第一个ip为客户ip
		 if (ip != null && ip.indexOf(",") != -1) {
		  ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim();
		 }
		 return ip;
	}

		@SuppressWarnings("rawtypes")
		public static String getChangeByMap(Map<String, Object> m, String type) {
			type = type==null?"修改":type;

			String change = type + ":";
			Set set = m.entrySet();
			Iterator iterator = set.iterator();
			while (iterator.hasNext()) {
				Map.Entry mapentry = (Map.Entry) iterator.next();
				if (mapentry.getValue() != null && !mapentry.getValue().equals("")) {
					change = change + mapentry.getKey() + "[" + mapentry.getValue()
							+ "],";
				}
			}
			return change;
		}

		public static String getChangeByMap(HashMap<String, Object> hm, String type) {
			Map<String, Object> m = hm;
			return getChangeByMap(m, type);
		}
		
		
		public static String getChangeByObject(Object obj, String type) throws Exception {
			type = type==null?"修改":type;

			String change = type + ":";
			
			Field[] fields = obj.getClass().getDeclaredFields();
			for (Field field : fields) {
				String key = field.getName();
				boolean access = field.isAccessible();
				if (!access)
					field.setAccessible(true);
				Object value = field.get(obj);
				if (!access)
					field.setAccessible(false);
				change = change + key + "[" + value+ "],";
			}
			return change;
		}
}
